package com.ff.sca.dealData.controller;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.ff.kvm.common.dv.es.UserESDV;
import com.ff.kvm.common.third_util.WXPublicUtil;
import com.ff.kvm.common.util.Constants;
import com.ff.kvm.common.util.MyUtil;
import com.ff.kvm.team.consumer.TeamConsumer;
import com.ff.sca.admin.service.RedisService;
import com.ff.sca.common.base.BaseController;
import com.ff.sca.common.entity.resmsg.ResMsg;
import com.ff.sca.common.util.CharUtil;
import com.ff.sca.common.util.DateUtil;
import com.ff.sca.dealData.entity.Address;
import com.ff.sca.dealData.entity.User;
import com.ff.sca.dealData.service.IAddressService;
import com.ff.sca.dealData.service.IUserService;
import com.ff.sca.user.entity.KvmAccount;
import com.ff.sca.user.entity.KvmAddress;
import com.ff.sca.user.entity.KvmUser;
import com.ff.sca.user.service.IKvmAccountService;
import com.ff.sca.user.service.IKvmAddressService;
import com.ff.sca.user.service.IKvmUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Controller
@RequestMapping("/dealData")
public class DealDataController extends BaseController {

    @Autowired
    private IUserService userService;
    @Autowired
    private IAddressService addressService;


    @Autowired
    private IKvmUserService kvmUserService;
    @Autowired
    private IKvmAddressService kvmAddressService;
    @Autowired
    private IKvmAccountService kvmAccountService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private TeamConsumer teamConsumer;

    @ResponseBody
    @RequestMapping(value = "/test", method = RequestMethod.GET)
    public ResMsg test(String id) {
        String data = getUnionid(id);
        return resSuccess(data);
    }


    /**
     * 处理用户数据
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/data", method = RequestMethod.GET)
    public ResMsg data() {
        try {
            List<User> userList = userService.selectList(new EntityWrapper<User>().orderBy("id", true));
            if (userList.size() > 0) {
                for (int i = 0; i < userList.size(); i++) {
                    User user = userList.get(i);
                    if (CharUtil.isNotEmpty(user.getTel())) {//手机号为空，无效用户
                        int count = kvmUserService.selectCount(new EntityWrapper<KvmUser>().eq("user_code", user.getTel()));
                        if (count == 0) {
                            //------用户-----
                            KvmUser kvmUser = new KvmUser();
                            if (CharUtil.isNotEmpty(user.getCreatetime())) {
                                kvmUser.setCreateTime(new Date(Long.parseLong(user.getCreatetime().toString() + "000")));
                            }
                            if (CharUtil.isNotEmpty(user.getUpdatetime())) {
                                kvmUser.setUpdateTime(new Date(Long.parseLong(user.getUpdatetime().toString() + "000")));
                            }
                            kvmUser.setTeamProductLv(user.getStar());
                            kvmUser.setTeamGiftLv(user.getSale());
                            String mobile = user.getTel();
                            if (mobile.length() > 11) {
                                mobile = user.getTel().trim().replace(" ", "").replace("-", "");
                                Pattern pat = Pattern.compile("[\\u4e00-\\u9fa5]");
                                Matcher mat = pat.matcher(mobile);
                                mobile = mat.replaceAll("");
                            }
                            kvmUser.setUserName(mobile);
                            kvmUser.setMobile(mobile);
                            kvmUser.setNickName(user.getNickname());
                            //公众号下唯一id
                            kvmUser.setOpenid(user.getOpenid());
                            //微信唯一id
                            kvmUser.setUnionid(getUnionid(user.getOpenid()));
                            kvmUser.setName(user.getRealname());
                            kvmUser.setHeadUrl(user.getHeadimg());
                            kvmUser.setDealPwd(user.getPassword());
                            kvmUser.setUserCode(mobile);
                            //设置上级code
                            if (user.getRecommendId().equals("god")) {
                                kvmUser.setPollCode("888888");
                                kvmUser.setFloor(1);
                            } else {
                                User parentUser = userService.selectOne(new EntityWrapper<User>().eq("user_id", user.getRecommendId()));
                                kvmUser.setPollCode(parentUser.getTel());
                            }
                            //用户状态
                            kvmUser.setStatus(0);
                            kvmUser.setLv(user.getLevel());
                            kvmUser.setDirectGiftTimes((new Double(user.getScore3())).intValue());
                            kvmUserService.insert(kvmUser);
                            //------账户-----
                            KvmUser user1 = kvmUserService.selectOne(new EntityWrapper<KvmUser>().eq("user_code", kvmUser.getUserCode()));
                            KvmAccount account = new KvmAccount();
                            account.setUserId(user1.getId());
                            account.setMd(user.getWallet());
                            account.setGwj(user.getScore());
                            account.setCreateTime(kvmUser.getCreateTime());
                            kvmAccountService.insert(account);
                            //------收货地址------
                            List<Address> addressesList = addressService.selectList(new EntityWrapper<Address>().eq("user_id", user.getUserId()));
                            if (addressesList.size() > 0) {
                                for (int t = 0; t < addressesList.size(); t++) {
                                    Address address = addressesList.get(t);
                                    KvmAddress address2 = new KvmAddress();
                                    //处理省市
                                    String[] addArr = address.getAddress().split(" ");
                                    address2.setProvice(addArr[0]);
                                    address2.setCity(addArr[1]);
                                    if (addArr.length == 3) {
                                        address2.setArea(addArr[2]);
                                    }
                                    address2.setUserId(user1.getId());
                                    address2.setName(address.getRealname());
                                    address2.setMobile(address.getTel());
                                    address2.setDetail(address.getDetail());
                                    if (CharUtil.isNotEmpty(address.getCreatetime())) {
                                        address2.setCreateTime(new Date(Long.parseLong(address.getCreatetime().toString() + "000")));
                                    }
                                    if (address.getStatus() == 1) {
                                        address2.setIsDefault(1);
                                    }
                                    kvmAddressService.insert(address2);
                                }
                            }
                        }
                    }
                }
            }
            rf = 0;
            //处理楼层
            List<KvmUser> userList1 = kvmUserService.selectList(null);
            if (userList1.size() > 0) {
                dealFloor(userList1);
            }
            //存入楼层
            redisService.putAppCache("user_floor", String.valueOf(rf));
            return resSuccess(null);
        } catch (Exception e) {
            e.printStackTrace();
            return resError(e.getMessage());
        }
    }

    private String getUnionid(String openId) {
        return WXPublicUtil.getUnionId(getAccessToken(), openId);
    }

    private String getAccessToken() {
        String accessToken = redisService.getAppCache(Constants.WX_PUBLIC_ACCESS_TOKEN2);
        if (!MyUtil.isBlank(accessToken) && !MyUtil.isBlank(accessToken.split("-----")[1])) {
            Date lastTime = MyUtil.getDateH(new Date(), -2);
            Date dateTime = MyUtil.parseDate(accessToken.split("-----")[0]);
            if (!MyUtil.before(dateTime, lastTime)) {
                return accessToken.split("-----")[1];
            }
        }
        accessToken = WXPublicUtil.getPublicAccessToken();
        if (!MyUtil.isBlank(accessToken)) {
            redisService.putAppCache(Constants.WX_PUBLIC_ACCESS_TOKEN2, MyUtil.formatDateYMDhms(new Date()) + "-----" + accessToken);
        }
        return accessToken;
    }

    private void dealFloor(List<KvmUser> list) {
        for (int i = 0; i < list.size(); i++) {
            KvmUser user = list.get(i);
            if (CharUtil.isNotEmpty(user.getUserCode())) {
                user.setFloor(GetFloor(user));
                kvmUserService.updateById(user);
                //es
                UserESDV esuserdv = new UserESDV();
                esuserdv.setUserId(user.getId());
                esuserdv.setCreateTime(user.getCreateTime());
                esuserdv.setFloor(user.getFloor());
                esuserdv.setLv(user.getLv());
                KvmUser upuser = kvmUserService.selectOne(new EntityWrapper<KvmUser>().eq("user_code", user.getPollCode()));
                if (upuser != null) {
                    esuserdv.setUpUserId(upuser.getId());
                }
                esuserdv.setStatus(user.getStatus());
                esuserdv.setTeamGiftLv(user.getTeamGiftLv());
                esuserdv.setTeamProductLv(user.getTeamProductLv());
                teamConsumer.addUser(esuserdv);
            }
        }
    }

    private static int rf = 0;

    private int GetFloor(KvmUser user) {
        int floor = 1;
        KvmUser user1 = kvmUserService.selectOne(new EntityWrapper<KvmUser>().eq("user_code", user.getPollCode()));
        if (user1 != null) {
            floor += GetFloor(user1);
        }
        if (rf < floor) {
            rf = floor;
        }
        return floor;
    }

}

